package com.mindata.blockchain.socket.handler.server;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.core.manager.DbBlockManager;
import com.mindata.blockchain.socket.base.AbstractBlockHandler;
import com.mindata.blockchain.socket.body.base.ViewChangeBody;
import com.mindata.blockchain.socket.packet.BlockPacket;
import com.mindata.blockchain.socket.common.msg.ViewChangeMsg;
import com.mindata.blockchain.socket.common.queue.base.MsgQueueManager;
import com.mindata.blockchain.socket.common.queue.ViewChangeQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import javax.annotation.Resource;

/**
 * handler 的作用是将收到的消息进行处理的地方
 * viewchange 更换视图
 * 发生条件：当主节点崩溃时，并超过时间片之后会主动出发视图更换
 */
public class ViewChangeHandler extends AbstractBlockHandler<ViewChangeBody> {
    private Logger logger = LoggerFactory.getLogger(ViewChangeHandler.class);
    @Resource
    ViewChangeQueue viewChangeQueue;
    @Resource
    DbBlockManager dbBlockManager;

    @Override
    public Class<ViewChangeBody> bodyClass() {
        return ViewChangeBody.class;
    }


    @Override
    public Object handler(BlockPacket packet, ViewChangeBody viewChangeBody, ChannelContext channelContext) throws Exception {
        ViewChangeMsg viewChangeMsg = viewChangeBody.getViewChangeMsg();
        // 判断 view 请求消息的view和本地view的关系并采取相应措施

//        dbBlockManager.getLastBlockNumber()
        ApplicationContextProvider.getBean(MsgQueueManager.class).pushMsg(viewChangeMsg);
        logger.info("收到来自于<{}><更换视图>消息，更换视图信息为[{}]", viewChangeMsg.getToView(), viewChangeMsg);
        return null;
    }
}
